package blogs.eidos.cloud.framework.core.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * @author ： Eidos
 * @date ：Created in 2021/1/25
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Aspect
@Component
@Slf4j
public class DefaultControllerLogAspect {
    /**
     * 对所有的接口 添加日志 日志信息有 请求地址 被请求地址 请求参数
     *
     * @param joinPoint
     */
    @Before("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
    public void restLogAccessBefore(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String remoteAddr = requestAttributes.getRequest().getRemoteAddr();
            String url = requestAttributes.getRequest().getRequestURI();
//            ClientInfo clientInfo = ClientInfoUtil.get(HttpServletRequestUtil.getRequest());
            log.debug("************************************************************");
            log.debug("*                                                          *");
            log.debug("*                      接口请求开始                        *");
            log.debug("*                                                          *");
            log.debug("************************************************************");
            log.debug("接口请求开始时间：" + LocalDateTime.now());
            log.debug("接口请求remoteAddr：" + remoteAddr);
            log.debug("接口请求url：" + url);
            log.debug("接口请求参数：" + JSON.toJSONString(joinPoint.getArgs(), SerializerFeature.IgnoreNonFieldGetter));
        } catch (Exception e) {
            log.error("服务请求异常" + e);
        }
    }


    @After("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
    public void restLogAccessAfter(JoinPoint joinPoint) {
        try {
            log.debug("接口请求结束时间：" + LocalDateTime.now());
            log.debug("************************************************************");
            log.debug("*                                                          *");
            log.debug("*                      接口请求结束                        *");
            log.debug("*                                                          *");
            log.debug("************************************************************");
        } catch (Exception e) {
            log.error("服务请求异常" + e);
        }
    }

}
